<?php
/**
 * @fileName:  File.php
 * @author:    LiaoJiangYi
 * @datetime:  2017/1/16 19:31
 * @QQ:        527532113
 * @weChat:    jyliao_vip
 * @email:     jyliao@vip.qq.com
 * @website:   http://www.jyliao.com
 */
namespace Ext;
final class File
{
    private static function mimeType($mimeType)
    {
        $_mimeType = array(
            'image/jpeg' => array('jpg', 'jpeg', 'jpe'),
            'image/gif' => 'gif',
            'image/x-png' => 'png',
            'image/png' => 'png',
            'application/pdf' => 'pdf',
            'application/msword' => 'doc',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
            'application/vnd.ms-powerpoint' => 'ppt',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
            'application/vnd.ms-excel' => 'xls',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
            'text/comma-separated-values' => 'csv',
            'application/x-shockwave-flash' => 'swf',
            'application/rar' => 'rar',
            'application/zip' => 'zip',
            'video/mp4' => 'mp4',
            'audio/mpeg' => array('mp3', 'mpga', 'mpega', 'mp2', 'm4a')
        );
        if (empty($_mimeType[$mimeType])) return false;
        if (is_array($_mimeType[$mimeType])) return $_mimeType[$mimeType];
        else return array($_mimeType[$mimeType]);
    }

    /**
     * 获取文件扩展名
     * @param $file 文件绝对地址
     * @return false|array
     * */
    public static function getExtension($file)
    {
        $fInfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($fInfo, $file);
        finfo_close($fInfo);
        return self::mimeType($mimeType);
    }

    /**
     * 格式化 文件大小单位
     */
    public static function formatBytes($bytes)
    {
        if ($bytes >= 1073741824) {
            $bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
        } elseif ($bytes >= 1048576) {
            $bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
        } elseif ($bytes >= 1024) {
            $bytes = round($bytes / 1024 * 100) / 100 . 'KB';
        } else {
            $bytes = $bytes . 'Bytes';
        }
        return $bytes;
    }
}